package com.freecloud.javabasics.design.proxy.cglib;

import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLib代理类，需要实现MethodInterceptor接口，并使用Enhancer创建新的被代理类
 * 使用继承方式实现动态代理
 *
 * 坑：目标代理类不能有final修饰，否则会忽略
 * @Author: maomao
 * @Date: 2019-11-22 11:23
 */
public class CGLibProxy implements MethodInterceptor {

    private Object target;

    public Object createProxyObject(Object object){
        this.target = object;
        //设置cglib生成新类的class位置
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,"/Users/maomao/Downloads");

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(object.getClass());
        enhancer.setCallback(this);

        Object newProxyObj = enhancer.create();


        return newProxyObj;
    }

    @Override
    public  Object  intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("使用CGLib，找工作");
        Object result = method.invoke(target,objects);
        System.out.println("找到工作，准备面试！");

        return result;
    }
}
